package com.linkage.usercenter.schedule;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.linkage.common.constant.CommonSysConstant;
import com.linkage.common.util.RedisUtils;
import com.linkage.usercenter.dao.CoreDptInfoMapper;
import com.linkage.usercenter.dao.CoreUserMapper;
import com.linkage.usercenter.dao.MgrLoginDailyMapper;
import com.linkage.usercenter.pojo.entity.CoreUser;
import com.linkage.usercenter.pojo.entity.MgrLoginDaily;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
public class UserMgrSchedule {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MgrLoginDailyMapper mgrLoginDailyMapper;
    @Autowired
    private CoreUserMapper userMapper;

    @Scheduled(cron = "0 30 23 * * ?")
    public void userMgrStatisticsDaily(){
        log.info("开始执行登录统计定时任务");
        // 查询redis中所有管理员的key
        Set<String> keys = redisUtils.keys("TOKEN:*:GLY-45-4:*");
        Map<String,Integer> map = new HashMap<>();
        // 按部门分类，统计当天登录数量，放入数据库中
        for (String key: keys){
            String dptCode = key.split(":")[1];
            if(!map.containsKey(dptCode)){
                map.put(dptCode,1);
            }else{
                int count = map.get(dptCode);
                //移除对应键值对，防止重复
                map.remove(dptCode);
                map.put(dptCode,count+1);
            }
        }
        log.info("查询到"+map.size()+"条信息");
        //保存登录信息到表中
        List<MgrLoginDaily> list = new ArrayList<>();
        map.forEach((x,y) ->{
            int total = 0;
            List<CoreUser> userList1 = userMapper.queryUserByDptWithPersonClass(x,"4");
            List<CoreUser> userList2 = userMapper.queryUserByDptWithPersonClass(x,"5");
            if(ObjectUtil.isNotEmpty(userList1)){
                total += userList1.size();
            }
            if(ObjectUtil.isNotEmpty(userList2)){
                total += userList2.size();
            }
            list.add(MgrLoginDaily.builder().dptCode(x).loginCount(y).noLoginCount(total-y)
                    .loginDate(Integer.valueOf(DateUtil.format(new Date(),"yyyyMMdd"))).build());
        });
        if(list.size()>0){
            //批量插入统计表中
            mgrLoginDailyMapper.batchInsert(list);
        }
    }
}
